package com.android.lovely.ui.fragment

import android.view.ViewGroup
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.filter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.android.lovely.R
import com.android.lovely.admob.Ad
import com.android.lovely.admob.AdmobManager
import com.android.lovely.admob.showReword
import com.android.lovely.api.getRewardGemUseCase
import com.android.lovely.const.ChatChange
import com.android.lovely.data.ChatHistoryList
import com.android.lovely.databinding.FragmentChatListBinding
import com.android.lovely.databinding.ItemChatHistoryBinding
import com.android.lovely.ext.format
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.framework.BaseLoadAdapter
import com.android.lovely.framework.BaseLoadFragment
import com.android.lovely.framework.BaseLoadViewModel
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.framework.widget.FlexibleContentContainer
import com.android.lovely.manager.KVStore
import com.android.lovely.ui.activity.HomeActivity
import com.android.lovely.ui.chat.ChatMessageActivity
import com.android.lovely.ui.dialog.showLovelyDialog
import com.android.lovely.ui.viewmodel.ChatHistoryListViewModel
import com.android.lovely.ui.viewmodel.SearchViewModel
import com.android.lovely.user.UserManager
import com.kotlin.extensions.appContext
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.context.ContextExt.startPageClearTop
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.inflater.LayoutInflaterExt.layoutInflater
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull

/**
 *
 * @author why
 * @date 2025/3/11 16:53
 */
class ChatHistoryFragment :
    BaseLoadFragment<FragmentChatListBinding, ChatHistoryList>() {
    private val mViewModel by activityViewModels<ChatHistoryListViewModel>()
    override fun getViewModel(): BaseLoadViewModel<ChatHistoryList> {
        return mViewModel
    }

    override fun initView() {
        getRecyclerView().layoutManager = LinearLayoutManager(requireContext())
        val notice = KVStore.system?.appNotice.orEmpty()
        mBinding.carousel.text = notice
        mBinding.llCarousel.isVisible =
            notice.isNotEmpty() && KVStore.noticeContent != notice
        super.initView()
        viewLifecycleOwner.lifecycleScope.launchSafety {
            AdmobManager.chatAdEnableFlow.collectLatest {
                mBinding.free.isVisible = it
            }
        }
        mBinding.notifyClose.clickable {
            KVStore.noticeContent = notice
            mBinding.llCarousel.isVisible = false
        }
        mBinding.free.clickable {
            showFreeAd()
        }
        viewLifecycleOwner.lifecycleScope.launch {
            FlowBus.flowOf<ChatChange>().collectLatest {
                mBinding.srlRefresh.isRefreshing = true
                adapter.refresh()
            }
        }
    }

    private fun showFreeAd() {
        viewLifecycleOwner.lifecycleScope.launchWithLoading {
            withTimeoutOrNull(15000) {
                Ad.Chat.load()?.join()
            }
            requireActivity().showReword(Ad.Chat) {
                if (it) {
                    lifecycleScope.launchWithLoading {
                        getRewardGemUseCase("ad_in_chat_page").let {
                            UserManager.updateGems(it.getOrDefault("surplus", UserManager.userInfo?.point ?: 0))
                            showToast(getString(R.string.sign_success, (it.getOrDefault("point", 0)).toString()))
                        }
                        AdmobManager.startTimerFlow()
                    }.onError {
                        showToast(getString(R.string.ad_fail))
                    }
                } else {
                    showToast(getString(R.string.ad_fail))
                }
            }
        }
    }

    override fun getStateLayout(): FlexibleContentContainer {
        return mBinding.flexState
    }

    override fun getSwipeRefreshLayout(): SwipeRefreshLayout {
        return mBinding.srlRefresh
    }

    override fun getRecyclerView(): RecyclerView {
        return mBinding.rv
    }

    override fun setNoContent() {
        getStateLayout().setNoContentText(getString(R.string.no_history))
        getStateLayout().setNoContentIcon(R.drawable.icon_no_content)
        getStateLayout().setNoContentButton(getString(R.string.go_chat), true) {
            startPage<HomeActivity>("position" to 1)
        }
    }

    override fun getBaseAdapter(): BaseLoadAdapter<ChatHistoryList, *> {
        return ChatHistoryAdapter(mViewModel).apply {
            itemClickListener = { item, position ->
                requireActivity().startPageClearTop<ChatMessageActivity>("id" to item.botId)
            }
        }
    }

    override suspend fun initData() {
        mViewModel.pager.combine(mViewModel.removedFlow) { data, remove ->
            data.filter { it.id !in remove }
        }.collectLatest {
            adapter.submitData(it)
        }
    }
}

class ChatHistoryAdapter(val viewModel: ChatHistoryListViewModel) :
    BaseLoadAdapter<ChatHistoryList, ChatHistoryAdapter.ChatHistoryHolder>(
        object :
            DiffUtil.ItemCallback<ChatHistoryList>() {
            override fun areItemsTheSame(
                oldItem: ChatHistoryList,
                newItem: ChatHistoryList
            ): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(
                oldItem: ChatHistoryList,
                newItem: ChatHistoryList
            ): Boolean {
                return oldItem == newItem
            }

        }
    ) {
    override fun onBindViewHolder(p0: ChatHistoryHolder, p1: Int) {
        val item = getItem(p1) ?: return
        p0.binding.apply {
            setupAvatar(item)
            setupNameAndMessage(item)
            setupUnreadCount(item)
            setupLastReplyTime(item)
            itemRoot.clickable {
                itemClickListener?.invoke(item, p1)
            }
            itemRoot.setOnLongClickListener {
                itemRoot.context.showLovelyDialog {
                    setDialogTitle(appContext.getString(R.string.delete_history))
                    setDialogMessage(appContext.getString(R.string.delete_history_message))
                    setPositiveButton {
                        viewModel.delete(item.id)
                    }
                }
                true
            }
        }
    }

    private fun ItemChatHistoryBinding.setupAvatar(item: ChatHistoryList) {
        avatar.loadWithPlaceholder(item.avatar["url"]?.substringBefore("?"), R.drawable.icon_default_avatar)
    }

    private fun ItemChatHistoryBinding.setupNameAndMessage(item: ChatHistoryList) {
        name.text = item.name
        message.text = item.lastReply
    }

    private fun ItemChatHistoryBinding.setupUnreadCount(item: ChatHistoryList) {
        count.isVisible = item.unreadNum > 0
        count.text = getUnreadCountText(item.unreadNum)
    }

    private fun getUnreadCountText(unreadNum: Int): String {
        return if (unreadNum > 99) "99+\u0020" else "${unreadNum}\u0020"
    }

    private fun ItemChatHistoryBinding.setupLastReplyTime(item: ChatHistoryList) {
        if (item.lastReplyTimeInt > 0) {
            time.text = (item.lastReplyTimeInt * 1000L).format()
        } else {
            time.text = item.uTime
        }
    }


    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ChatHistoryHolder {
        return ChatHistoryHolder(p0)
    }

    class ChatHistoryHolder(
        parent: ViewGroup,
        val binding: ItemChatHistoryBinding = ItemChatHistoryBinding.inflate(
            parent.layoutInflater,
            parent,
            false
        )
    ) : RecyclerView.ViewHolder(binding.root)
}